package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String username =  req.getParameter("username");
        String password = req.getParameter("password");
        if(username == null || username.equals("") || password == null || password.equals("")) {
            String html = "<h3>缺少用户名或密码</h3>";
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        UserDao userDao = new UserDao();
        User user = userDao.selectUserByName(username);
        if(user == null) {
            String html = "<h3>用户名或密码错误</h3>";
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        if(!user.getPassword().equals(password)) {
            String html = "<h3>用户名或密码错误</h3>";
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        //设置session
        HttpSession session = req.getSession(true);
        session.setAttribute("user",user);
        //跳转页面
        resp.sendRedirect("list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        if(session == null) {
            //回话不存在
            resp.setStatus(403);
            return;
        }
        User user = (User)session.getAttribute("user");
        if(user == null) {
            //会话存在,但里面没对象
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        user.setPassword("");
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}
